package com.zgroup.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtils {

    public static String serialize(Object obj) throws IOException {
        return serialize(obj, "UTF-8");
    }

    public static String serialize(Object obj, String encode) throws IOException {
        if (CheckUtils.isEmpty(obj)) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        return URLEncoder.encode(baos.toString("ISO-8859-1"), encode);
    }

    public static Object unserialize(String serializeObj) throws IOException, ClassNotFoundException {
        return unserialize(serializeObj, "UTF-8");
    }

    public static Object unserialize(String serializeObj, String encode) throws IOException, ClassNotFoundException {
        if (CheckUtils.isEmpty(serializeObj)) {
            return null;
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(URLDecoder.decode(serializeObj, encode).getBytes("ISO-8859-1"));
        ObjectInputStream ios = new ObjectInputStream(bais);
        return ios.readObject();
    }

    public static String saveQuerySting(HttpServletRequest req, HttpServletResponse res) {
        return saveQuerySting(Constants.REQUEST_QUERY_STRING, req, res);
    }

    public static String saveQuerySting(String key, HttpServletRequest req, HttpServletResponse res) {
        String queryString = req.getQueryString();
        if ("POST".equals(req.getMethod().toUpperCase())) {
            queryString = makeQueryString(req.getParameterMap());
        }
        return saveQuerySting(key, queryString, res);
    }

    public static String saveQuerySting(String key, String queryString, HttpServletResponse res) {
        System.out.println("saveQuerySting:" + key + ":" + queryString);
        res.addCookie(new Cookie(key, queryString));
        return queryString;
    }

    public static String loadQuerySting(HttpServletRequest req, HttpServletResponse res) {
        return loadQuerySting(Constants.REQUEST_QUERY_STRING, req, res);
    }

    public static String loadQuerySting(String key, HttpServletRequest req, HttpServletResponse res) {
        String queryString = (String) ((Map) getInfoByCookie(req, new String[]{key})).get(key);
        System.out.println("loadQuerySting:" + key + ":" + queryString);
        return queryString;
    }

    public static Map fetchData(String[] keys, Map properties) {
        Map data = new HashMap();
        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        for (int i = 0; i < keys.length; i++) {
            String name = keys[i];
            Object value = properties.get(name);
            if (value instanceof String) {
                data.put(name, value);
            } else if (value instanceof String[]) {
                data.put(name, ((String[]) value)[0]);
            }
        }
        return data;
    }

    public static String makeQueryString(Map properties) {
        StringBuffer buf = new StringBuffer();
        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        while (names.hasNext()) {
            String name = (String) names.next();
            Object value = properties.get(name);
            if (CheckUtils.isEmpty(value)) {
                continue;
            }
            String temp = "";
            if (value instanceof String) {
                temp = (String) value;
            } else if (value instanceof String[]) {
                temp = ((String[]) value)[0];
            }
            try {
                buf.append("&" + name + "=" + URLEncoder.encode(temp, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (buf.length() == 0) {
            return "";
        }
        return buf.substring(1).toString();
    }

    public static List split(String text, String regex) {
        List list = new ArrayList();
        int start = 0;
        int pos = 0;
        int step = regex.length();
        while ((pos = text.indexOf(regex, start)) > -1) {
            list.add(text.substring(start, pos));
            start = pos + step;
        }
        list.add(text.substring(start));
        return list;
    }

    public static List split(String text) {
        List list = new ArrayList();
        for (int i = 0; i < text.length(); i++) {
            list.add(text.charAt(i));
        }
        return list;
    }

    public static String ltrim(String text, char ch) {
        int pos = 0;
        for (; pos < text.length(); pos++) {
            if (ch != text.charAt(pos)) {
                break;
            }
        }
        return text.substring(pos);
    }

    public static String rtrim(String text, char ch) {
        int pos = text.length() - 1;
        for (; pos > 0; pos--) {
            if (ch != text.charAt(pos)) {
                break;
            }
        }
        return text.substring(0, pos + 1);
    }

    public static String replace(String text, int begin, int end, char ch) {
        StringBuffer buff = new StringBuffer(text);
        for (int i = begin; i < end; i++) {
            buff.setCharAt(i, ch);
        }
        return buff.toString();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
//		Map log = new Hashtable();
//		log.put("ID", WebUtils.generateUuidHex());
//
//		log.put("CREATE_DATE", "わたし私");
//
//		String text = serialize(log, "UTF-8");
//		System.out.println("serialize:"+text);
//		System.out.println("unserialize:"+(Map)unserialize(text, "UTF-8"));
        System.out.println(getPYString("汉字"));

    }

    public static void populate(Map bean, Map properties) {

        // Do nothing unless both arguments have been specified
        if ((bean == null) || (properties == null)) {
            return;
        }

        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        while (names.hasNext()) {
            // Identify the property name and value(s) to be assigned
            String name = (String) names.next();
            if (name == null) {
                continue;
            }
            Object value = properties.get(name);
            if (value instanceof String) {
                bean.put(name, value);
            } else if (value instanceof String[]) {
                bean.put(name, ((String[]) value)[0]);
            }
        }
    }

    public static String getSeverletPart(String url) {
        int pos = url.lastIndexOf("/");
        return url.substring(pos);
    }

    public static String getFileExt(String fileName, boolean toLowerCase) {
        String ext = "";
        int pos = fileName.lastIndexOf(".");
        if (pos > -1) {
            ext = fileName.substring(pos);
        }
        if (toLowerCase) {
            ext = ext.toLowerCase();
        }
        return ext;
    }

    /**
     * 根据keys从cookie取得相应的值
     *
     * @param request
     * @param keys
     * @return
     */
    public static Map<String, String> getInfoByCookie(HttpServletRequest request, String[] keys) {
        Map<String, String> info = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < keys.length; i++) {
                for (int j = 0; j < cookies.length; j++) {
                    if (cookies[j].getName().equals(keys[i])) {
                        info.put(keys[i], cookies[j].getValue());
                        break;
                    }
                }
            }
        }
        return info;
    }

    public static String getKeyByValue(Map map, String text) {
        if (CheckUtils.isEmpty(text)) {
            return null;
        }
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            if (text.indexOf((String) entry.getValue()) > -1) {
                return (String) entry.getKey();
            }
        }
        return null;
    }

    public static String generateUuidHex() {
        return java.util.UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getTime(String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(Calendar.getInstance().getTime());
    }

    public static int getDaysOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static String formatTime(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static String getCreateDate() {
        return getTime("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 取得文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > -1) {
            return fileName.substring(pos).toLowerCase();
        }
        return "";
    }

    /**
     * 生成随机字符串
     *
     * @param size 随机字符串长度
     * @return
     * @author clb
     * @modify 2008-5-30
     * @since 2008-5-30
     */
    public static String getRandomString(int size) {
        char[] c =
                {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r',
                        't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h',
                        'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'};
        Random random = new Random(); // 初始化随机数产生器
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            sb.append(c[Math.abs(random.nextInt()) % c.length]);
        }
        return sb.toString();
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        copy(in, out, false);
    }

    public static void copy(InputStream in, OutputStream out, boolean notClose) throws IOException {
        int size = 1024;
        byte[] b = new byte[size];
        while ((size = in.read(b)) > 0) {
            out.write(b, 0, size);
        }
        if (notClose) {
            out.close();
            in.close();
        }

    }

    /**
     * 汉字转拼音缩写
     *
     * @param str //要转换的汉字字符串
     * @return String  //拼音缩写
     */
    public static String getPYString(String str) {
        String tempStr = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if ((c >= '0' && c <= '9')
                    || (c >= 'A' && c <= 'z')) {//字母和数字原样保留
                tempStr += String.valueOf(c);
            } else if (Character.isLetter(c)) {//中文
                tempStr += getPYChar(String.valueOf(c));
            }
        }
        return tempStr;
    }

    /**
     * 取单个字符的拼音声母
     *
     * @param c //要转换的单个汉字
     * @return String 拼音声母
     */
    public static String getPYChar(String c) {
        byte[] array = new byte[2];
        array = String.valueOf(c).getBytes();
        int i = (short) (array[0] - '\0' + 256) * 256 + ((short) (array[1] - '\0' + 256));
        if (i < 0xB0A1) return c;
        if (i < 0xB0C5) return "A";
        if (i < 0xB2C1) return "B";
        if (i < 0xB4EE) return "C";
        if (i < 0xB6EA) return "D";
        if (i < 0xB7A2) return "E";
        if (i < 0xB8C1) return "F";
        if (i < 0xB9FE) return "G";
        if (i < 0xBBF7) return "H";
        if (i < 0xBFA6) return "J";
        if (i < 0xC0AC) return "K";
        if (i < 0xC2E8) return "L";
        if (i < 0xC4C3) return "M";
        if (i < 0xC5B6) return "N";
        if (i < 0xC5BE) return "O";
        if (i < 0xC6DA) return "P";
        if (i < 0xC8BB) return "Q";
        if (i < 0xC8F6) return "R";
        if (i < 0xCBFA) return "S";
        if (i < 0xCDDA) return "T";
        if (i < 0xCEF4) return "W";
        if (i < 0xD1B9) return "X";
        if (i < 0xD4D1) return "Y";
        if (i < 0xD7FA) return "Z";
        return c;
    }
}
